﻿using System;
using System.Globalization;
using System.Text;
using System.Web;

namespace Altairis.Web {

    public static class ExtensionMethods {

        /// <summary>
        /// Gets full URL of this application root, including last slash.
        /// </summary>
        /// <param name="rq">The current HttpRequest.</param>
        /// <returns>Full URL of this application root, including last slash.</returns>
        public static Uri ApplicationBaseUri(this HttpRequest rq) {
            UriBuilder ub = new UriBuilder(rq.Url);
            ub.Path = rq.ApplicationPath;
            ub.Query = string.Empty;
            ub.Fragment = string.Empty;
            if (!ub.Path.EndsWith("/")) ub.Path += "/";
            return ub.Uri;
        }

        public static string CreateKey(this string s) {
            if (string.IsNullOrEmpty(s)) return string.Empty;
            s = s.RemoveDiacritics().ToLower();
            s = System.Text.RegularExpressions.Regex.Replace(s, "[^a-z0-9]", "-");
            s = s.Trim('-');
            while (s.IndexOf("--") > -1) s = s.Replace("--", "-");
            return s;
        }

        /// <summary>
        /// Removes diacritic marks from string.
        /// </summary>
        /// <param name="s">String to be stripped off diacritic marks.</param>
        /// <returns>Supplied string where all characters with diacritic marks are replaced with their base characters.</returns>
        public static string RemoveDiacritics(this string s) {
            s = s.Normalize(NormalizationForm.FormD);
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < s.Length; i++) {
                if (CharUnicodeInfo.GetUnicodeCategory(s[i]) != UnicodeCategory.NonSpacingMark) sb.Append(s[i]);
            }
            return sb.ToString().Normalize(NormalizationForm.FormC);
        }

        /// <summary>
        /// Sends the error response.
        /// </summary>
        /// <param name="rp">The HttpResponse.</param>
        /// <param name="statusCode">The status code.</param>
        /// <param name="statusDescription">The status description.</param>
        /// <param name="message">The error message.</param>
        public static void SendErrorResponse(this HttpResponse rp, int statusCode, string statusDescription, string message) {
            rp.ContentType = "text/html";
            rp.StatusCode = statusCode;
            rp.StatusDescription = statusDescription;
            rp.Output.WriteLine(Properties.Resources.GenericErrorResponsePage, statusCode, statusDescription, message);
            rp.End();
        }
    }
}